package com.yskj.mwk.utils;

import cn.hutool.core.date.DateUtil;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yskj.mwk.bean.GoodsSpec;
import org.json.JSONArray;
import org.json.JSONObject;

import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

public class GenerateGoodsSkuUtil {

    public static void main(String[] args) throws Exception {

    }

    public List<GoodsSpec> generate(String jsonString){
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            JsonNode rootNode = objectMapper.readTree(jsonString);

            // 提取JSON字符串中的数组和对应的key
            Iterator<Map.Entry<String, JsonNode>> fields = rootNode.fields();
            List<String> keys = new ArrayList<>();
            List<List<String>> arrays = new ArrayList<>();
            while (fields.hasNext()) {
                Map.Entry<String, JsonNode> entry = fields.next();
                keys.add(entry.getKey());
                arrays.add(new ArrayList<>());
                for (JsonNode element : entry.getValue()) {
                    arrays.get(arrays.size() - 1).add(element.asText());
                }
            }

            // 生成所有可能的搭配
            List<GoodsSpec> goodsSpecList = new ArrayList<>();
            List<Map<String, String>> combinations = generateAllCombinations(arrays, keys, 0, new HashMap<>());
            for (Map<String, String> combination : combinations) {
                String str = combinationToString(combination);
                String index = getIndex(combination, rootNode);
                GoodsSpec goodsSpec = new GoodsSpec();
                goodsSpec.setOwn_spec(str);
                goodsSpec.setIndexes(index);
                goodsSpecList.add(goodsSpec);
                //System.out.println("{own_spec:\"" + str + "\",indexes:\"" + index + "\"}");
            }
            return goodsSpecList;
        }catch (Exception e){
            return null;
        }
    }

    private List<Map<String, String>> generateAllCombinations(List<List<String>> arrays, List<String> keys, int index, Map<String, String> currentCombination) {
        List<Map<String, String>> result = new ArrayList<>();
        if (index == arrays.size()) {
            result.add(new HashMap<>(currentCombination));
            return result;
        }

        for (String item : arrays.get(index)) {
            Map<String, String> newCombination = new HashMap<>(currentCombination);
            newCombination.put(keys.get(index), item);
            result.addAll(generateAllCombinations(arrays, keys, index + 1, newCombination));
        }

        return result;
    }

    private String combinationToString(Map<String, String> combination) {
        return combination.entrySet().stream()
                .map(entry -> "\"" + entry.getKey() + "\":\"" + entry.getValue() + "\"")
                .collect(Collectors.joining(",", "{", "}"));
    }

    private String getIndex(Map<String, String> combination, JsonNode rootNode) {
        List<Integer> indices = new ArrayList<>();
        for (Iterator<Map.Entry<String, JsonNode>> it = rootNode.fields(); it.hasNext(); ) {
            Map.Entry<String, JsonNode> entry = it.next();
            String key = entry.getKey();
            String value = combination.get(key);
            JsonNode arrayNode = entry.getValue();
            int index = -1;
            for (int i = 0; i < arrayNode.size(); i++) {
                if (arrayNode.get(i).asText().equals(value)) {
                    index = i;
                    break;
                }
            }
            indices.add(index);
        }
        return String.join("-", indices.stream().map(Object::toString).collect(Collectors.toList()));
    }

    /**
     * 获取前端购物车展示规格
     * */
    public String getSpecStr(String specStr){
        JSONObject jsonObject = new JSONObject(specStr);
        StringBuilder specValue= new StringBuilder();
        for (String key : jsonObject.keySet()) {
            Object value = jsonObject.get(key);
            specValue.append(value).append(" ");

        }
        return specValue.toString();
    }
}
